#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018, Niklas Hauser
#
# This file is part of the modm project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

from collections import OrderedDict

def init(module):
    module.name = ":driver:gpio_sampler"
    module.description = "Gpio Sampling via Interrupts"


def prepare(module, options):
    if options[":target"].identifier["platform"] != "stm32":
        return False

    core = options[":target"].get_driver("core:cortex-m*")
    # Cortex-M0 doesn't have the DWT->CYCCNT and Cortex-M7 support is broken
    if not core or "m0" in core["type"] or "m7" in core["type"]:
        return False

    module.depends(
        ":platform:gpio",
        ":platform:exti",
        ":platform:core",
        ":architecture:interrupt")
    return True


def build(env):
    exti_vectors = [v["name"] for v in env[":target"].get_driver("core")["vector"] if "EXTI" in v["name"]]
    # These are all exti possible vectors: 0..15, 0_1, 15_10, 2_3, 2_TSC, 4_15, 9_5
    extimap = {
        "0": [0], "1": [1], "2": [2], "3": [3], "4": [4],
        "5": [5], "6": [6], "7": [7], "8": [8], "9": [9],
        "10": [10], "11": [11], "12": [12], "13": [13], "14": [14],
        "15" : [15],
        "0_1": [0,1],
        "2_TSC": [2],
        "2_3": [2,3],
        "4_15": [4,5,6,7,8,9,10,11,12,13,14,15],
        "9_5": [5,6,7,8,9],
        "15_10": [10,11,12,13,14,15],
    }
    extis = OrderedDict()
    for v in sorted(exti_vectors):
        extis[v] = extimap[v[4:]]

    env.substitutions = {
        "extis": extis,
        "vectors_location": env.get(":platform:core:vector_table_location", "rom"),
    }
    env.outbasepath = "modm/src/modm/driver"
    env.template("gpio_sampler.cpp.in")
    env.template("gpio_sampler.hpp.in")
    env.template("gpio_sampler_impl.hpp.in")
